import subprocess,threading
from project.settings import MEDIA_ROOT
from django.shortcuts import render, redirect
from django.views.generic.base import View
from django.http import HttpResponse, JsonResponse,StreamingHttpResponse
from django.core.paginator import Paginator
from django.views.decorators.cache import cache_page
from django.urls import reverse
from .models import *
from .forms import *
from .serializers import *
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.db.models import Q

def search_videos(request):
    query = request.GET.get('keywords', '')
    results = []

    if query:
        results = Video_web1.objects.filter(Q(name__icontains=query)).order_by('-id')
    # 每页显示的对象数量
    per_page = 8

    # 创建Paginator对象
    paginator = Paginator(results, per_page)
    # 获取当前页码，默认为1
    print(paginator.num_pages)
    page_number = request.GET.get('page')

    videos = paginator.get_page(page_number)

    count =paginator.count
    return render(request, 'video/videos/search.html', {'query': query, 'videos': videos,'count':count})
def extract_first_frame_with_moviepy(video_path, output_image_path):
    # print(MEDIA_ROOT+'/videos/'+video_path)
    # print(MEDIA_ROOT+'/videos/'+output_image_path)
    from moviepy.editor import VideoFileClip
    from PIL import Image
    import numpy as np
    # 打开视频文件
    clip = VideoFileClip(MEDIA_ROOT+'/videos/'+video_path)

    # 提取第一帧
    frame = clip.get_frame(0)

    # 将numpy数组转换为Pillow图像对象
    image = Image.fromarray(np.uint8(frame))

    # 保存第一帧为图片
    image.save(MEDIA_ROOT+'/videos/'+output_image_path)

    print("第一帧已保存为图片")

def convert_mp4_to_m3u8(file,name):
    file=MEDIA_ROOT+'/videos/'+file
    file_dir=MEDIA_ROOT+'/videos/'+name

    print(file)
    print(file_dir)
    cmd = f"ffmpeg -i {file} -c:v libx264 -c:a aac -f hls -hls_segment_filename {file_dir}/%d.ts -hls_list_size 0 {file_dir}/index.m3u8"
    subprocess.run(cmd, shell=True)

    print("视频已经切片且生成m3u8文件")

def video_upload(request):
    if request.method == 'GET':
        return render(request, 'video/videos/video_upload.html', {'form_obj': MyModelForm()})
    if request.method == 'POST':
        f = MyModelForm(request.POST, request.FILES)

        if f.is_valid():
            print()
            video1 = Video_web1()
            video1.name = f.cleaned_data['name']
            video1.save()
            video1.file = f.cleaned_data['video']
            video1.m3u8 = 'videos/' +str(video1.id)+   '/index.m3u8'
            video1.picture='videos/' +str(video1.id)+   '/first_frame.jpg'
            video1.user_id=request.user.id
            video1.category_id=1
            video1.save()
            #生成视频片段和m3u8片段
            print(request.FILES['video'])
            threading.Thread(target=convert_mp4_to_m3u8,args=(str(video1.id)+'/original.mp4',str(video1.id)+'/')).start()
            #生成第一帧图片
            threading.Thread(target=extract_first_frame_with_moviepy,args=(str(video1.id)+'/original.mp4',str(video1.id)+'/first_frame.jpg')).start()
            return JsonResponse({'msg':'已上传服务器，等待审核'})
        else:
            print(f.errors)
            return JsonResponse({'msg':'上传失败，请联系网站管理员'})


def stream_video2(request, arg_path):
    path = MEDIA_ROOT+'/videos/' + arg_path
    video_file = open(path, 'rb')
    response = StreamingHttpResponse(video_file, content_type='video/mp4')
    return response

def play(request, arg_path):
    video=Video_web1.objects.get(pk=arg_path)
    return render(request, 'video/videos/play.html', {'video':  video})

def author(request, arg_path):
    video_obj = Video_web1.objects.all()
    # 每页显示的对象数量
    per_page = 8
    # 创建Paginator对象
    paginator = Paginator(video_obj, per_page)
    # 获取当前页码，默认为1
    page_number = request.GET.get('page')
    obj = paginator.get_page(page_number)
    return render(request, 'video/videos/author.html', {'obj':  obj})

def fenlei(request):
    video_obj = Video_web1.objects.all().order_by('-id')
    # 每页显示的对象数量
    per_page = 8
    # 创建Paginator对象
    paginator = Paginator(video_obj, per_page)
    # 获取当前页码，默认为1
    print(paginator.num_pages)
    page_number = request.GET.get('page')
    obj = paginator.get_page(page_number)
    return render(request, 'video/videos/video分类.html', {'obj':  obj})



#@cache_page(timeout=60 * 1, cache='default')
def index(request):
    video_obj = Video_web1.objects.all().order_by('-id')
    # 每页显示的对象数量
    per_page = 12
    # 创建Paginator对象
    paginator = Paginator(video_obj, per_page)
    # 获取当前页码，默认为1
    page_number = request.GET.get('page')
    obj = paginator.get_page(page_number)
    return render(request,'video/videos/index.html',{'obj':obj,'request':request})


class VideosCategoryView(View):
    def get(self, request):
        cates = VideosCategory.objects.all()
        return render(request, "back/videos/cate_index.html", {"cates": cates})


class VideosCategoryAddView(View):
    def __init__(self):
        self.alist = {}

    def binddata(self, datas, id, n):
        if id == 0:
            datas = datas.filter(parent__isnull=True)
        else:
            datas = datas.filter(parent__isnull=True)
        for data in datas:
            self.alist[data.id] = self.spacelength(n) + data.name
            self.binddata(datas, data.id, n + 2)
        return self.alist

    def spacelength(self, i):
        space = ''
        for j in range(1, i):
            space += "&nbsp;&nbsp;"
        return space + "|--"

    def get(self, request):
        form_obj = VideosCategoryForm()
        return render(request, "back/videos/cate_add.html", {"form_obj": form_obj})

    def post(self, request):
        form_obj = VideosCategoryForm(request.POST, request.FILES)
        if form_obj.is_valid():
            name = request.POST.get("name", '')
            cates = VideosCategory.objects.filter(name=name)
            if cates:
                info = '分类已经存在'
            else:
                # form_obj.cleaned_data["is_staff"]=1
                # form_obj.cleaned_data["is_superuser"]=0 #非管理员
                # 接收页面传递过来的参数，进行新增
                cate = VideosCategory.objects.create(**form_obj.cleaned_data)
                # 成功后，重定向到商品分类列表页面
                # info='注册成功,请登陆'
                return redirect('cate_index')
            return render(request, 'video/goods/cate_index.html', {"form_obj": form_obj, "info": info})
        else:
            errors = form_obj.errors
            print(errors)
            return render(request, "video/goods/cate_add.html", {'form_obj': form_obj, 'info': errors})


class VideosView(View):

    def get(self, request):
        cates = Video_web1.objects.all()
        page_size = 8
        try:
            curr_page = int(request.GET.get("page", 1))
        except ValueError:
            curr_page = 1
        paginator = Paginator(cates, page_size)
        try:
            videos = paginator.page(curr_page)
        except PageNotAnInteger:
            videos = paginator.page(1)
        except EmptyPage:
            # 如果请求的页码超出范围，则显示最后一页
            videos = paginator.page(paginator.num_pages)
        return render(request, "back/videos/index.html", {"videos": videos})

    def post(self, request):
        pass


def VideosDelete(request,id):
    obj = Video_web1.objects.get(id=id)
    obj.delete()
    return redirect(reverse('videos_index'))


class VideosAddView(View):


    def spacelength(self, i):
        space = ''
        for j in range(1, i):
            space += "&nbsp;&nbsp;"
        return space + "|--"


    def get(self, request):
        form_obj = VideosForm()
        cates= VideosCategory.objects.all()
        return render(request, "video/videos/video_upload.html", {"form_obj": form_obj,'cates':cates})

    def post(self, request):
        f = MyModelForm(request.POST, request.FILES)
        if f.is_valid():
            video1 = Video_web1()
            video1.file = request.FILES['video']
            video1.name = request.POST.get('name')
            video1.m3u8 = 'videos/' + request.POST.get('name') + '/output.m3u8'
            video1.save()
            convert_mp4_to_m3u8(str(request.FILES['video']), request.POST.get('name'))

            return HttpResponse('上传完成!')
        else:
            return HttpResponse('上传失败!')

